import {SimplePipe} from './simple-pipe';
import {Type} from '@angular/core';
import {getProperty, setProperty} from '../functions/core';
import {deepCopy} from '../functions/copy';
import {DynamicComponent, DynamicComponentEvent, DynamicComponentOptions} from '../components/dynamic-component/dynamic-component.interface';

/**
 * 简单json对象的格式化输出(简单json对象指的是不内嵌json对象)
 * */
export class SimpleJsonFormatter {

  constructor(public propName: string,
              public displayName: string,
              public sort?: boolean,
              public component?: Type<DynamicComponent>,
              public dynamicComponent?: DynamicComponentOptions,
              public events?: DynamicComponentEvent, // component中的事件处理
              public pipe?: SimplePipe) {
  }

  static formatDataSet(simpleJsonFormatter: SimpleJsonFormatter[], dataSet: object[]) {
    return dataSet.map((item) => {
      return this.formatSingleData(simpleJsonFormatter, item);
    });
  }

  static formatSingleData(simpleJsonFormatter: SimpleJsonFormatter[], data: object) {
    const _data = deepCopy(data);
    for (const formatter of simpleJsonFormatter) {
      if (formatter.pipe) {
        if (!formatter.pipe.args) {
          formatter.pipe.args = [];
        }
        const formattedData = formatter.pipe.pipeTransform.transform(
          getProperty(data, formatter.propName),
          ...formatter.pipe.args, {originData: data, formatter: formatter}
        );
        setProperty(_data, formatter.propName, formattedData);
      }
    }
    return _data;
  }
}
